//
//  UIColor+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import Foundation

public extension UIColor {
    /// 从字符串构造颜色
    ///
    /// - parameter hexString: 16进制字符串,RGA(#FFFFFF)或者ARGB(#FFFFFFFF)
    convenience init?(hexString: String) {
        let hexString: NSString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
        let scanner            = Scanner(string: hexString as String)

        if hexString.hasPrefix("#") {
            scanner.scanLocation = 1
        }

        var color: UInt32 = 0
        if !scanner.scanHexInt32(&color) {
            return nil
        }

        let mask = 0x000000FF
        var a = 255
        if hexString.length > 7 {
            a = Int(color >> 24) & mask
        }
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask

        let alpha = CGFloat(a) / 255.0
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0

        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }

    /// 从整数构造颜色
    ///
    /// - parameter rgbaColor: 用整数表示的颜色(0xFFFFFFFF)
    convenience init?(rgbaColor: UInt) {
        let red = CGFloat(rgbaColor & 0xFF000000) / 255
        let green = CGFloat(rgbaColor & 0x00FF0000) / 255
        let blue = CGFloat(rgbaColor & 0x0000FF00) / 255
        let alpha = CGFloat(rgbaColor & 0x000000FF) / 255
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    /// 从整数构造颜色
    ///
    /// - parameter rgbColor: 用整数表示的颜色(0xFFFFFF)
    convenience init?(rgbColor: UInt) {
        self.init(rgbaColor: (rgbColor<<8)|0x000000FF)
    }

    /// 从整数构造颜色
    ///
    /// - parameter rgbColor: 用整数表示的颜色(0xFFFFFF)
    /// - parameter alpha: [0, 1]区间
    convenience init?(rgbColor: UInt, alpha: CGFloat) {
        let red = CGFloat(rgbColor & 0xFF0000) / 255
        let green = CGFloat(rgbColor & 0x00FF00) / 255
        let blue = CGFloat(rgbColor & 0x0000FF) / 255
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }

    /// 返回颜色的16进制字符串表达
    ///
    /// - returns: 16进制字符串
    func toHexString() -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0

        getRed(&r, green: &g, blue: &b, alpha: &a)

        let rgb: Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0

        return NSString(format:"#%06x", rgb) as String
    }
}
